package com.wr.services.impl;

import com.wr.mappers.RoleMapper;
import com.wr.mappers.RolePermissionEntityMapper;
import com.wr.pojos.RoleEntity;
import com.wr.pojos.RolePermissionEntity;
import com.wr.services.RoleService;
import com.wr.utils.PageInfo;
import com.wr.utils.Utils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 角色Service实现类
 *
 * @author StarZou
 * @since 2014年6月10日 下午4:16:33
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RolePermissionEntityMapper rolePermissionEntityMapper;

    @Override
    public List<RoleEntity> selectRolesByUserId(String userId) {
        return roleMapper.selectRolesByUserId(userId);
    }

    @Override
    public List<RoleEntity> selectRoleList(PageInfo pageInfo) {
        pageInfo.setCount(roleMapper.countRoles());
        List<RoleEntity> list = roleMapper.selectRoleList(new RowBounds(pageInfo.getOffset(),pageInfo.getPageSize()));
        return list;
    }

    @Override
    @Transactional
    public void saveRolePermission(int array[],int roleId) {
        rolePermissionEntityMapper.deleteByRoleId(roleId);
        for (int i : array){
            RolePermissionEntity rolePermissionEntity = new RolePermissionEntity();
            rolePermissionEntity.setRoleId(roleId);
            rolePermissionEntity.setPermissionId(i);
            rolePermissionEntityMapper.insert(rolePermissionEntity);
        }
    }

    @Override
    @Transactional
    public void insertRole(int[] array, RoleEntity roleEntity) {
        roleEntity.setCreateTime(Utils.formatLongDate(new Date()));
        roleEntity.setUpdateTime(Utils.formatLongDate(new Date()));
        roleMapper.insert(roleEntity);

        if(roleEntity.getId()!=0){
            for (int i : array){
                RolePermissionEntity rolePermissionEntity = new RolePermissionEntity();
                rolePermissionEntity.setRoleId(roleEntity.getId());
                rolePermissionEntity.setPermissionId(i);
                rolePermissionEntityMapper.insert(rolePermissionEntity);
            }
        }else{
            throw new RuntimeException();
        }
    }

    @Override
    public List<RoleEntity> selectRoles() {
        return roleMapper.selectRoles();
    }
}
